package cn.javabb.project.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.javabb.common.exception.DBException;
import cn.javabb.common.model.domain.AjaxResult;
import cn.javabb.framework.util.DBUtil;
import cn.javabb.framework.web.controller.BaseController;
import cn.javabb.framework.web.page.TableDataInfo;
import cn.javabb.project.entity.SysDataSource;
import cn.javabb.project.service.SysDataSourceService;
import cn.javabb.project.util.GenUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @desc:
 * @author: javabb (javabob(a)163.com)
 * @create: 2021/04/29 17:13
 */
@Api(tags = "数据源管理")
@RestController
@RequestMapping("/datasource")
public class DataSourceController extends BaseController {
    @Autowired
    private SysDataSourceService sysDataSourceService;
    @ApiOperation("分页查询数据源")
    @GetMapping("/")
    public TableDataInfo list(SysDataSource dsc) {
        startPage();
        List<SysDataSource> list = sysDataSourceService.list(dsc);
        return getDataTable(list);
    }
    @ApiOperation("根据ID查询数据源")
    @GetMapping("/{id}")
    public AjaxResult getOne(@PathVariable Long id) {
        return AjaxResult.success(sysDataSourceService.getById(id));
    }
    @ApiOperation("新增数据源")
    @PostMapping("/")
    public AjaxResult save(@RequestBody SysDataSource dsc) {
        dsc.setStatus("0");
        dsc.setCreateTime(new Date());
        dsc.setUpdateTime(new Date());
        if (sysDataSourceService.save(dsc)) {
            return AjaxResult.success("保存成功");
        }
        return AjaxResult.error("保存失败");
    }
    @ApiOperation("更新数据源")
    @PutMapping("/")
    public AjaxResult update(@RequestBody SysDataSource dsc) {
        dsc.setUpdateTime(new Date());
        if (sysDataSourceService.updateById(dsc)) {
            return AjaxResult.success("更新成功");
        }
        return AjaxResult.error("更新失败");
    }
    @ApiOperation("删除数据源")
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable Long id) {
        if (sysDataSourceService.removeById(id)) {
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }
    /**
     * 测试成功
     * @return
     */
    @ApiOperation("测试数据源可用")
    @PostMapping("/test")
    public AjaxResult testLink(@RequestBody SysDataSource sds) {
        new DBUtil(GenUtil.getDataSourceConfig(sds));
        return AjaxResult.success("连接成功");
    }
}
